/*
 * Creates the GUI.
 * Licensed by the Bunie Developmentgroup.
 */

package infoserver;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

/**
 * This class creates the GUI, with this class you're able to start the InfoServer
 */
public class ServerGUI extends JFrame {

    private JComponent contentPane;
    private JPanel north, west, south, east, center;
    private JLabel JLPortnumber;
    private JTextField JTFPortnummer;
    protected TextArea chat;
    private JButton JBChangePortnumber, start, stop;
    private Server myServer;
    private JMenuBar menubar;
    private JMenu menuFile, menuView;
    private JMenuItem itemLog, itemClose;
    private int portnumber = 1025;
    private final static Logger LOGGER = Logger.getLogger(Log.class.getName());
    public boolean started = false;

    /**
     * Creates a GUI for the server. Possible to change portnumber and start the
     * server. Default portnumber is 1024.
     * 
     * @author Wouter Brunekreeft
     * @since v0.1
     */
    public ServerGUI() {
        super("Server console");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        contentPane = (JComponent) this.getContentPane();
        contentPane.setLayout(new BorderLayout());
        setSize(400, 400);
        makeLayout();
		setIcons();
        
        Log.setup();
        LOGGER.setLevel(Level.INFO);
            
        this.setVisible(true);
        contentPane.setVisible(true);
    }
	
	/**
	 * Set the icons
	 * @author Kay van Bree
	 */
	public void setIcons(){
		ArrayList imageList = new ArrayList();
		imageList.add(Toolkit.getDefaultToolkit().getImage("bunie50x50.png"));
		setIconImages(imageList);
	}

    /**
     * Layout is divided into 5 segments Let's make it!
     *
     * @author Wouter Brunekreeft
     * @since v0.1
     *
     */
    private void makeLayout() {
        makeMenu();
        makeCenter();
        makeNorth();
        makeWest();
        makeSouth();
        makeEast();
    }
    
    /**
     * Makes the Menu. 
     * 
     * @author: Patrick Wobben
     * @since: v0.1
	 * @version: v0.9
     * 
     */
    private void makeMenu() {
        menubar = new JMenuBar();
        
        this.setJMenuBar(menubar);
         
        menuFile = new JMenu("File");
        menuView = new JMenu("View");
        itemClose = new JMenuItem("Close");
        itemLog = new JMenuItem("View Log");
        
        menubar.add(menuFile);
        menubar.add(menuView);
        menuFile.add(itemClose);
        menuView.add(itemLog);
        
        itemClose.addActionListener(new ActionListener() {
            @Override
             public void actionPerformed(ActionEvent e) {
                 System.exit(0);
             }
        });
        itemLog.addActionListener(new ActionListener() {
            @Override
             public void actionPerformed(ActionEvent e) {
				viewLog();
			}
        });
    }

    /**
     * Creates center: textarea for notification current port.
     *
     * @author Wouter Brunekreeft
     * @since v0.1
     */
    private void makeCenter() {
		
        center = new JPanel();
        contentPane.add(center, BorderLayout.CENTER);
        center.setBackground(Color.white);
    }

    /**
     * Creates north: label and button. Possibility to change port number.
     *
     * @author Wouter Brunekreeft, Patrick Wobben
     * @since v0.1
     */
    private void makeNorth() {
		
        JPanel north = new JPanel();
		north.setPreferredSize(new Dimension(10,50));
		
		contentPane.add(north, BorderLayout.NORTH);
        north.setBackground(Color.white);
		
        JLPortnumber = new JLabel("Portnumber");
        north.add(JLPortnumber);
		
        JTFPortnummer = new JTextField(5);
        north.add(JTFPortnummer);
		
        JBChangePortnumber = new JButton("Change");
        north.add(JBChangePortnumber);
        // Note that portnumber is changed
        JBChangePortnumber.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    portnumber = Integer.parseInt(JTFPortnummer.getText());
                    String message = "The portnumber is now: ";
                    chat.setText(message + " \n" +  portnumber);
                    print(message + portnumber);
                } catch (NumberFormatException ex) {
                    //Exception if portnumber is wrong
                    print("Invalid portnumber submitted please enter numeric");
                }
            }
        });
    }

    /**
     * Creates west: button for stop and stopfunction server
     *
     * @author Wouter Brunekreeft, Patrick Wobben
     * @since v0.1
     */
    private void makeWest() {
        west = new JPanel();
		west.setPreferredSize(new Dimension(150,100));
        contentPane.add(west, BorderLayout.WEST);
        west.setBackground(Color.white);
        stop = new JButton("Stop");
        west.add(stop);

        stop.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                LOGGER.info("Server is stopping");
                System.exit(0);
            }
        });
    }

    /**
     * Creates south (white Jpanel)
     *
     * @author Wouter Brunekreeft
     * @since v0.1
     */
	
    private void makeSouth() {
        south = new JPanel();
        contentPane.add(south, BorderLayout.SOUTH);
        south.setBackground(Color.white);
		
		chat = new TextArea(13, 25);
        south.add(chat);
        
        String message = "Current port number: ";
        chat.setText(message +  " \n" + portnumber + "\n");
        print(message + portnumber);
    }
    
    /**
     * View the log
     * @author Patrick Wobben
     * @since v0.9
     */
	
    public void viewLog() {
		JFrame frame = new JFrame("Log");
        frame.setSize(600,400);
        TextArea textarea = new TextArea(100,50);
        textarea.setEditable(false);
                 
        try {
			FileReader text = new FileReader("infoserver-log.txt");
            BufferedReader buffer = new BufferedReader(text);
            String s;
            
			try {
				while((s=buffer.readLine())!= null){
					textarea.append(s);
                    textarea.append("\n");
                }
				text.close();
            } catch (IOException ex){ }   
         } catch(FileNotFoundException ex){ }
        frame.getContentPane().add(textarea);
        frame.setVisible(true);
    }
    
    /**
     * Creates east: button for Start and startfunction for server.
     *
     * @author Wouter Brunekreeft, Patrick Wobben
     * @since v0.1
     */
    private void makeEast() {
        east = new JPanel();
        contentPane.add(east, BorderLayout.EAST);
        east.setBackground(Color.white);

        start = new JButton("Start");
        east.add(start);
        start.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                start.setEnabled(false);
                JBChangePortnumber.setEnabled(false);
                JTFPortnummer.setEnabled(false);
                started=true;
                new Thread("Server") {
                    @Override
                    public void run() {
                        myServer = new Server(portnumber);
                        LOGGER.info("Starting Server");
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException ex) {
                        } catch (IllegalArgumentException ex) {
                        } 
                    }
                }.start();
            }
        });
    }
    
    /**
 * Prints a message.
 * @param message (type = String)
 */
    
    private static void print(String message) {
       // System.out.println("Server: "+message);
        LOGGER.info(message);
    }
}